<?php

namespace App\Kuafu\Shop\Service;

use App\Exceptions\BaseException;
use App\Kuafu\Audit\Enum\AuditEventCodeEnum;
use App\Kuafu\Audit\Service\AuditService;
use App\Kuafu\Base\Enum\DBEnum;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Common\Service\InformationPushService;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Mqtt\Service\MqttService;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Order\Model\Clickhouse\OrderCHModel;
use App\Kuafu\Order\Service\OrderPayService;
use App\Kuafu\Pay\Channel\FuYou\FuYouBase;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Product\Enum\ProductCodeEnum;
use App\Kuafu\Product\Exceptions\ProductException;
use App\Kuafu\Product\Model\Product;
use App\Kuafu\ProductMenu\Enum\ProductMenuCodeEnum;
use App\Kuafu\ProductMenu\Exceptions\ProductMenuException;
use App\Kuafu\ProductMenu\Model\ProductMenu;
use App\Kuafu\Shop\Enum\CodeEnum as ShopEnum;
use App\Kuafu\Shop\Enum\ShopCacheEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\AreaModel;
use App\Kuafu\Shop\Model\CollectShopListModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopBusinessCKModel;
use App\Kuafu\Shop\Model\ShopBusinessModel;
use App\Kuafu\Shop\Model\ShopOperateTargetModel;
use App\Kuafu\Shop\Model\ShopPaymentsModel;
use App\Kuafu\Shop\Model\ShopProductStatus;
use App\Kuafu\Shop\Resources\merchant\CityShopListResource;
use App\Kuafu\Shop\Resources\merchant\ShopListResource;
use App\Kuafu\Shop\Validate\ShopValidate;
use App\Kuafu\Sys\Model\Menus;
use App\Kuafu\User\Enum\CodeEnum as UserCodeEnum;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Enum\UserEnum;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Model\Role;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserRoleService;
use App\Kuafu\User\Service\UserService;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\Clickhouse\WaiMaiOrderCHModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\WaiMaiShopService;
use App\Library\FeiShu\SendFs;
use App\Library\KfHttp\TigerCurl;
use App\Library\Redis\RedisHelp;
use App\Library\TencentMap\TencentMapHelp;
use App\Remote\Tiger\OpenShop\OpenShopRemote;
use App\Remote\Tiger\OrganizationManage\OrganizationManageRemote;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Kuafu\File\FileUtil;
use Psr\SimpleCache\InvalidArgumentException;
use Tinderbox\Clickhouse\Exceptions\ClientException;
use function Symfony\Component\String\s;


class ShopStatisticsService extends BaseService
{
    /**
     * 查询时间段
     *
     * @var array
     */
    protected array $date = [];

    /**
     * 对比时间段
     *
     * @var array
     */
    protected array $comparedDate = [];

    /**
     * 查询时间段
     *
     * @param array $date
     * @return $this|false
     */
    public function setDate(array $date)
    {
        if (empty($date['startAt']) || empty($date['endAt'])) {
            return false;
        }

        $this->date = $date;

        $this->setComparedDate([
            'startAt' => date('Y-m-d', strtotime($date['startAt']) - 7 * 86400),
            'endAt'   => date('Y-m-d', strtotime($date['endAt']) - 7 * 86400),
        ]);

        return $this;
    }

    /**
     * 对比时间段
     *
     * @param array $comparedDate
     * @return $this
     */
    public function setComparedDate(array $comparedDate): ShopStatisticsService
    {
        $this->comparedDate = $comparedDate;
        return $this;
    }

    /**
     * 排序
     *
     * @param string $column
     * @param string $sort
     * @return $this
     */
    protected array $orderBy = [];

    /**
     * 排序
     *
     * @param string $column
     * @param string $sort
     * @return $this
     */
    public function setOrderBy(string $column, string $sort = 'desc'): ShopStatisticsService
    {
        $columnsList = array_keys($this->getWindCloudColumn());

        if (!in_array($column, $columnsList)) {
            $column = array_pop($columnsList);
        }

        if (!in_array($sort, ['asc', 'desc'])) {
            $sort = 'desc';
        }

        $this->orderBy = [
            'column' => $column,
            'sort'   => $sort
        ];
        return $this;
    }

    protected int $pageNum  = 0;
    protected int $pageSize = 10;

    /**
     * 设置分页
     *
     * @param int $page
     * @param int $pageSize
     * @return $this
     */
    public function setPage(int $page = 0, int $pageSize = 10): ShopStatisticsService
    {
        $this->pageNum  = $page;
        $this->pageSize = $pageSize;
        return $this;
    }

    /**
     * 获取排序
     *
     * @return array|string[]
     */
    public function getOrderBy(): array
    {
        if (empty($this->orderBy)) {
            return [
                'column' => 'orderReceivedAmountSum',
                'sort'   => 'desc'
            ];
        } else {
            return $this->orderBy;
        }
    }

    /**
     * @throws ClientException
     */
    private function getShopBusinessData($date, Collection $shopList): Collection
    {
//        return $this->getShopBusinessDataClickhouse($date, $shopList);

        // 判断日期是否是今天
        if ($date['startAt'] == $date['endAt'] && $date['startAt'] == date('Y-m-d')) {
            return $this->getShopBusinessDataClickhouse($date, $shopList);
        } else {
            return $this->getShopBusinessDataMysql($date, $shopList);
        }

    }


    /**
     * 从 mysql 获取营业数据
     *
     * @param $date
     * @param $shopList
     * @return mixed
     */
    private function getShopBusinessDataMysql($date, $shopList)
    {
        $key  = 'getWindCloudData-Business_new_0130_100:' . implode('-', $date) . ':' . md5($shopList);
        $list = Cache::remember($key, Carbon::now()->addDays(30), function () use ($date, $shopList) {
            $fields = [
                'shopId',
                'shopCode',
                raw('sum(orderReceivedAmount) as orderReceivedAmountSum'),
                raw('sum(canteenOrderReceivedAmount) as canteenOrderReceivedAmountSum'),
                raw('sum(takeawayOrderReceivedAmount) as takeawayOrderReceivedAmountSum'),
                raw('sum(orderTurnover) as orderTurnoverSum'),
                raw('sum(canteenOrderTurnover) as canteenOrderTurnoverSum'),
                raw('sum(takeawayOrderTurnover) as takeawayOrderTurnoverSum'),
            ];

            $list     = collect();
            $shopList = $shopList->toArray();
            ShopBusinessCKModel::query()
                               ->select($fields)
                               ->whereBetween('date', array_values($date))
                               ->whereIn('shopId', $shopList)
                               ->groupBy(raw('shopId, shopCode'))
                               ->orderBy('orderReceivedAmountSum')
                               ->chunk(10, function ($chunkList) use (&$list) {
                                   $list = $list->merge($chunkList);
                               });

            return $list->toArray();
        });

        $list = collect($list);

        if (!($list->count())) {
            Cache::forget($key);
        }

        return $list;
    }

    /**
     * 从 ClickHouse 获取今日的营业数据
     *
     * @param $date
     * @param Collection $shopList
     * @return Collection
     */
    private function getShopBusinessDataClickhouse($date, Collection $shopList): Collection
    {
        // 删除测试店
        $shopList = $shopList->flip()->forget(13315)->flip()->values();

        $cacheKey = 'getShopBusinessDataClickhouse:' . implode('-',
                $this->date) . ':' . md5($shopList);

//        $result = Cache::remember($cacheKey. time(), 0, function () use ($date, $shopList) {
        $result = Cache::remember($cacheKey, Carbon::now()->addMinutes(5), function () use ($date, $shopList) {
            $shopList = $shopList->toArray();

            $startTimestamp = strtotime($date['startAt']);
            $endTimestamp   = strtotime($date['endAt']) + 86399;

            // 获取堂食的营业数据
            $orderStatistic = OrderCHModel::query()
                                          ->select(raw('shopId,
                                    sum(realPayPrice) as canteenOrderReceivedAmountSum,
                                    sum(originalPrice) as canteenOrderTurnoverSum'))
                                          ->whereBetween('completeTime', [$startTimestamp, $endTimestamp])
                                          ->whereIn('shopId', $shopList)
                                          ->groupBy('shopId')
                                          ->get()
                                          ->keyBy('shopId');

            // 获取外卖的营业数据

            // 外卖营业额  ($shopTakeOutOrder->sum('originalPrice') - $shopTakeOutOrder->sum('originalShippingPrice') - $shopTakeOutOrder->sum('packingPrice')),
            /**
             * select count(1), sum(originalPrice)-sum(originalShippingPrice), sum(expectIncome)  from kf_waimai_order_1.kf_waimai_orders where shopId = 13112
             * and createdAt between 1681747200 and 1681833599
             * and orderStatus != 7
             * limit 1000;
             */
            $waimaiOrderStatistic = WaiMaiOrderCHModel::query()
                                                      ->select(raw('shopId,
                                   (sum(originalPrice)-sum(originalShippingPrice)) as takeawayOrderTurnoverSum,
                                   sum(expectIncome) as takeawayOrderReceivedAmountSum'
                                                      ))
                                                      ->whereBetween('createdAt', [$startTimestamp, $endTimestamp])
                                                      ->where('orderStatus', '!=', WaiMaiDBEnum::ORDER_STATUS_7)
                                                      ->whereIn('shopId', $shopList)
                                                      ->groupBy('shopId')
                                                      ->get()
                                                      ->keyBy('shopId');

            // 避免反复查库 获取 shopCode
            $shopCodeList = Cache::remember('getShopBusinessDataClickhouse_shop_code_list:' . md5(json_encode($shopList)),
                86400 * 30,
                function () use ($shopList) {
                    return Shop::query()->whereIn('id', $shopList)->select(['id', 'shopCode'])->get()->keyBy('id')
                               ->toArray();
                });
            // 组合堂食和外卖的数据

            /**
             * shopId => '',
             * shopCode => '',
             * orderReceivedAmountSum => '总实收',
             * canteenOrderReceivedAmountSum => '堂食实收',
             * takeawayOrderReceivedAmountSum => '外卖实收',
             * orderTurnoverSum => '总营业额',
             * canteenOrderTurnoverSum => '堂食营业额',
             * takeawayOrderTurnoverSum => '外卖营业额',
             */

            $result = [];
            foreach ($shopList as $shopId) {
                $canteenOrderReceivedAmountSum  = $orderStatistic[$shopId]['canteenOrderReceivedAmountSum'] ?? 0;
                $takeawayOrderReceivedAmountSum = $waimaiOrderStatistic[$shopId]['takeawayOrderReceivedAmountSum'] ?? 0;

                $canteenOrderTurnoverSum  = $orderStatistic[$shopId]['canteenOrderTurnoverSum'] ?? 0;
                $takeawayOrderTurnoverSum = $waimaiOrderStatistic[$shopId]['takeawayOrderTurnoverSum'] ?? 0;

                // 总实收
                $orderReceivedAmountSum = $canteenOrderReceivedAmountSum + $takeawayOrderReceivedAmountSum;

                // 过滤空数据
                if ($orderReceivedAmountSum == 0) {
                    continue;
                }
                $result[] = [
                    'shopId'                         => $shopId,
                    'shopCode'                       => $shopCodeList[$shopId]['shopCode'] ?? 0,
                    // 总实收
                    'orderReceivedAmountSum'         => bcdiv100($orderReceivedAmountSum),
                    // 堂食实收
                    'canteenOrderReceivedAmountSum'  => bcdiv100($canteenOrderReceivedAmountSum),
                    // 外卖实收
                    'takeawayOrderReceivedAmountSum' => bcdiv100($takeawayOrderReceivedAmountSum),
                    // 总营业额
                    'orderTurnoverSum'               => bcdiv100($canteenOrderTurnoverSum + $takeawayOrderTurnoverSum),
                    // 堂食营业额
                    'canteenOrderTurnoverSum'        => bcdiv100($canteenOrderTurnoverSum),
                    // 外卖营业额
                    'takeawayOrderTurnoverSum'       => bcdiv100($takeawayOrderTurnoverSum)
                ];
            }

            return collect($result)->values();
        });

        if ($result->count() == 0) {
            Cache::forget($cacheKey);
        }

        return $result;
    }

    /**
     * 字段说明
     *
     * @return string[]
     */
    public function getWindCloudColumn(): array
    {
        return [
            'orderReceivedAmountSum'              => '总实收',
            'canteenOrderReceivedAmountSum'       => '堂食实收',
            'takeawayOrderReceivedAmountSum'      => '外卖实收',
            'takeawayPercent'                     => '外卖占比',  // 外卖实收/总实收
            'orderReceivedAmountCompared'         => '实收同比',
            'canteenOrderReceivedAmountCompared'  => '堂食同比',
            'takeawayOrderReceivedAmountCompared' => '外卖同比',
            'orderTurnoverSum'                    => '总营业额',
            'canteenOrderTurnoverSum'             => '堂食营业额',
            'takeawayOrderTurnoverSum'            => '外卖营业额',
        ];
    }

    /**
     * 需要展示的字段
     *
     * @return string[]
     */
    public function showWindCloudColumn(): array
    {
        return [
            'orderReceivedAmountSum',
            'canteenOrderReceivedAmountSum',
            'takeawayOrderReceivedAmountSum',
            'takeawayPercent',
            'orderReceivedAmountCompared',
            'canteenOrderReceivedAmountCompared',
            'takeawayOrderReceivedAmountCompared',
            'orderTurnoverSum',
            'canteenOrderTurnoverSum',
            'takeawayOrderTurnoverSum',
        ];
    }

    protected $authUser;

    /**
     * @param int $kmsUserId
     * @return ShopStatisticsService
     * @throws UserException
     */
    public function checkUserStatus(int $kmsUserId = 0): ShopStatisticsService
    {
        if ($kmsUserId) {
            return $this;
        }
        $authUser = AuthService::getAuthUser();
        if ($authUser['status'] != 0) {
            throw new UserException(\App\Kuafu\User\Enum\UserCodeEnum::ERR_USER_STATUS);
        }

        $this->authUser = $authUser;
        return $this;
    }


    protected Collection $shopList;


    /**
     * @param string $shopName 店铺名称+编号模糊搜索
     * @param string $city 城市搜索
     * @param string $province 省份
     * @param string $district 区
     * @param string $branch 所属分公司
     * @param int $userId 用户id 从kms请求直接传
     * @param bool $isKms
     * @param array $provinceCodes
     * @param array $cityCodes
     * @param array $areaCodes
     * @param array $shopIds
     * @return $this
     * @throws BaseException
     * @throws GuzzleException
     * @throws ShopException
     */
    public function setShopList(
        string $shopName = '',
        string $city = '',
        string $province = '',
        string $district = '',
        string $branch = '',
        int $userId = 0,
        bool $isKms = true,
        array $provinceCodes = [],
        array $cityCodes = [],
        array $areaCodes = [],
        array $shopIds = []
    ): ShopStatisticsService {
        if (!$userId) {
            $userId = $this->authUser['id'];
        }
        $shopList       = ShopService::shopListDb($userId, true, $shopName, 0, 0, 1, 10000, ['id'], [], true,
            $city, $province, $district, $branch, $isKms, $provinceCodes, $cityCodes, $areaCodes, $shopIds) ?? [];
        $this->shopList = collect($shopList)->pluck('id')->filter();

        return $this;
    }

    private function checkToday(): bool
    {
        $date = $this->date;
        return $date['startAt'] == $date['endAt'] && $date['startAt'] == date('Y-m-d');
    }

    /**
     * @return array
     */
    public function getWindCloud(): array
    {
        $shopList = $this->shopList;

        $columnsList = array_keys($this->getWindCloudColumn());
        $cacheKey    = 'getWindCloudData102:' . implode('-',
                $this->date) . ':' . md5($shopList) . ':' . md5(implode(',',
                $columnsList));

        if (self::checkToday()) {
            $ttl = Carbon::now()->addMinutes(5);
        } else {
            $ttl = Carbon::now()->addDays(30);
        }

//        list($list, $total) = Cache::remember($cacheKey . time(), $ttl,
        list($list, $total) = Cache::remember($cacheKey, $ttl,
            function () use ($shopList, $columnsList) {
                $originData        = $this->getShopBusinessData($this->date, $shopList)->keyBy('shopId');
                $originDataShopIds = $originData->keys();

                $comparedData = $this->getShopBusinessData($this->comparedDate, $shopList)->keyBy('shopId');
                $shopNameList = ShopService::getShopListByShopIds($originDataShopIds, ['*'])
                                           ->keyBy('id');
                $list         = collect();
                foreach ($originData as $originDatum) {
                    $originDatumShopId = $originDatum['shopId'];
                    // 店铺名
                    $oneData['shopName'] = CommonService::zeroFill($shopNameList[$originDatumShopId]['shopCode']) . $shopNameList[$originDatumShopId]['name'] ?? '';
                    $oneData['shopId']   = $originDatumShopId;
                    $oneData['shopCode'] = CommonService::zeroFill($shopNameList[$originDatumShopId]['shopCode']);
                    foreach ($columnsList as $column) {
                        $oneData[$column] = (string)($originDatum[$column] ?? 0);
                    }
                    // 外卖占比
                    $oneData['takeawayPercent'] = (string)self::divZero($oneData['takeawayOrderReceivedAmountSum'],
                            $oneData['orderReceivedAmountSum']) * 100;

                    // 实收同比
                    $oneData['orderReceivedAmountCompared'] = (string)self::calcCompared($originDatum,
                            $comparedData[$originDatumShopId] ?? [],
                            'orderReceivedAmountSum') * 100;
                    // 堂食同比
                    $oneData['canteenOrderReceivedAmountCompared'] = (string)self::calcCompared($originDatum,
                            $comparedData[$originDatumShopId] ?? [],
                            'canteenOrderReceivedAmountSum') * 100;
                    // 外卖同比
                    $oneData['takeawayOrderReceivedAmountCompared'] = (string)self::calcCompared($originDatum,
                            $comparedData[$originDatumShopId] ?? [],
                            'takeawayOrderReceivedAmountSum') * 100;

                    $oneData['tags'] = [];

                    $list->prepend($oneData);
                }

                $comparedTotal = [
                    'orderReceivedAmountSum'         => 0,
                    'canteenOrderReceivedAmountSum'  => 0,
                    'takeawayOrderReceivedAmountSum' => 0,
                ];
                foreach ($comparedData as $comparedDataValue) {
                    $comparedTotal['orderReceivedAmountSum']         = bcadd($comparedTotal['orderReceivedAmountSum'],
                        $comparedDataValue['orderReceivedAmountSum'], 2);
                    $comparedTotal['canteenOrderReceivedAmountSum']  = bcadd($comparedTotal['canteenOrderReceivedAmountSum'],
                        $comparedDataValue['canteenOrderReceivedAmountSum'], 2);
                    $comparedTotal['takeawayOrderReceivedAmountSum'] = bcadd($comparedTotal['takeawayOrderReceivedAmountSum'],
                        $comparedDataValue['takeawayOrderReceivedAmountSum'], 2);
                }

                $total = collect();
                if ($list->count() > 0) {
                    foreach ($columnsList as $column) {
                        $total[$column] = bcadd($list->sum($column), 0, 2);
                    }
                    $total['orderReceivedAmountCompared']         = (string)self::calcCompared($total['orderReceivedAmountSum'],
                            $comparedTotal['orderReceivedAmountSum']) * 100;
                    $total['canteenOrderReceivedAmountCompared']  = (string)self::calcCompared($total['canteenOrderReceivedAmountSum'],
                            $comparedTotal['canteenOrderReceivedAmountSum']) * 100;
                    $total['takeawayOrderReceivedAmountCompared'] = (string)self::calcCompared($total['takeawayOrderReceivedAmountSum'],
                            $comparedTotal['takeawayOrderReceivedAmountSum']) * 100;
                    $total['takeawayPercent']                     = self::divZero($total['takeawayOrderReceivedAmountSum'],
                            $total['orderReceivedAmountSum'], 4) * 100;
                }
                $list = $list
                    ->keyBy('shopId')
                    ->sortByDesc('orderReceivedAmountSum')
                    ->map(function ($item) {
                        static $i = 0;
                        $i++;
                        if ($i > 3) {
                            return $item;
                        }
                        $item['tags'] = [
                            'ranking' => $i
                        ];
                        return $item;
                    });
                return [$list, $total];
            });

        if (!($list->count())) {
            Cache::forget($cacheKey);
        }

        $orderBy = $this->getOrderBy();
        if ($orderBy['sort'] == 'desc') {
            $list = $list->sortByDesc($orderBy['column']);
        } else {
            $list = $list->sortBy($orderBy['column']);
        }
        $list = $list->values();

        // 最后数据处理
        $resultList = $list
            ->forPage($this->pageNum, $this->pageSize)
            ->map(function ($item) {
                $this->getTotal($item);
                return $item;
            })
            ->values();

        if ($total->count()) {
            $this->getTotal($total);
        }

        $resultTotal = $total;

        return [
            'columns'    => $this->getWindCloudColumn(),
            'filter'     => [
                'sort'   => $this->orderBy['sort'],
                'column' => $this->orderBy['column']
            ],
//            'dateTab'    => self::getDateTab(),
            'list'       => $resultList,
            'total'      => $resultTotal,
            'totalCount' => $list->count(),
            'page'       => $this->pageNum,
        ];
    }


    /**
     * 获取时间卡
     *
     * @return array[]
     */
    private function getDateTab(): array
    {
        return [
            'today'     => [
                'text'    => '今天',
                'startAt' => Carbon::now()->startOfDay()->getTimestamp(),
                'endAt'   => Carbon::now()->endOfDay()->getTimestamp(),
            ],
            'yesterday' => [
                'text'    => '昨天',
                'startAt' => Carbon::yesterday()->startOfDay()->getTimestamp(),
                'endAt'   => Carbon::yesterday()->endOfDay()->getTimestamp(),
            ],
            'week'      => [
                'text'    => '本周',
                'startAt' => Carbon::now()->startOfWeek()->getTimestamp(),
                'endAt'   => Carbon::now()->endOfDay()->getTimestamp(),
            ],
            'month'     => [
                'text'    => '本月',
                'startAt' => Carbon::now()->startOfMonth()->getTimestamp(),
                'endAt'   => Carbon::now()->endOfDay()->getTimestamp(),
            ]
        ];
    }


    /**
     * 算同比/环比
     *
     * @param $oneData
     * @param $comparedData
     * @param string $key
     * @return int|string|null
     */
    private static function calcCompared($oneData, $comparedData, $key = '')
    {
        if (is_string($oneData) && is_string($comparedData)) {
            if (empty($oneData) || bccomp($comparedData, 0) == 0) {
                $result = 0;
            } else {
                $result = bcdiv(bcsub($oneData, $comparedData, 4), $comparedData, 4);
            }
            return $result;
        } else {
            if (empty($comparedData[$key]) || bccomp($comparedData[$key], 0) == 0) {
                $result = 0;
            } else {
                $result = bcdiv(bcsub($oneData[$key], $comparedData[$key], 4),
                    $comparedData[$key], 4);
            }
            return $result;
        }
    }

    /**
     * 做 被除数为 0 的 处理
     *
     * @param $oneData
     * @param $comparedData
     * @return int|string|null
     */
    private static function divZero($oneData, $comparedData, $scale = 4)
    {
        if (empty($oneData) || bccomp($comparedData, 0) == 0) {
            $result = 0;
        } else {
            $result = bcdiv($oneData, $comparedData, $scale);
        }
        return $result;
    }

    /**
     * @param $total
     */
    private function getTotal(&$total): void
    {
        $total['orderReceivedAmountSum']              = self::getUnit($total['orderReceivedAmountSum']);
        $total['canteenOrderReceivedAmountSum']       = self::getUnit($total['canteenOrderReceivedAmountSum']);
        $total['takeawayOrderReceivedAmountSum']      = self::getUnit($total['takeawayOrderReceivedAmountSum']);
        $total['orderTurnoverSum']                    = self::getUnit($total['orderTurnoverSum']);
        $total['canteenOrderTurnoverSum']             = self::getUnit($total['canteenOrderTurnoverSum']);
        $total['takeawayOrderTurnoverSum']            = self::getUnit($total['takeawayOrderTurnoverSum']);
        $total['takeawayPercent']                     = self::getUnit($total['takeawayPercent'], 1, 1, '%');
        $total['orderReceivedAmountCompared']         = self::getUnit($total['orderReceivedAmountCompared'], 1, 1, '%');
        $total['canteenOrderReceivedAmountCompared']  = self::getUnit($total['canteenOrderReceivedAmountCompared'], 1,
            1, '%');
        $total['takeawayOrderReceivedAmountCompared'] = self::getUnit($total['takeawayOrderReceivedAmountCompared'], 1,
            1, '%');
    }

    /**
     * 统一输出单位格式
     *
     * @param string $num 除数
     * @param int $divisor 被除数
     * @param int $scale 输出的小数位数
     * @param string $unit 单位
     * @return string
     */
    private static function getUnit(string $num, int $divisor = 1000, int $scale = 1, string $unit = 'K')
    {
        return bcadd(round(self::divZero($num, $divisor, $scale + 1), $scale), 0, $scale) . $unit;
    }


}
